<template>
  <view class="goods_list">
    <!-- 1.搜索框 -->
    <TopSearch></TopSearch>
    <!-- 2.tab栏 -->
    <u-tabs
      :list="tabs"
      :scrollable="false"
      :current="current"
      @click="click"
    ></u-tabs>
    <view v-if="current === 0">
      <navigator
        class="goods_item"
        v-for="item in goods"
        :key="item.goods_id"
        :url="'/pages/goods_detail/goods_detail?goods_id=' + item.goods_id"
      >
        <view class="goods_item_img">
          <image :src="item.goods_small_logo"></image>
        </view>
        <view class="goods_item_info">
          <view class="goods_name u-line-2">{{ item.goods_name }}</view>
          <view class="goods_price">¥{{ item.goods_price }}</view>
        </view>
      </navigator>
    </view>
    <view v-else-if="current === 1">销量</view>
    <view v-else-if="current === 2">价格</view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      tabs: [
        {
          name: "综合",
        },
        {
          name: "销量",
        },
        {
          name: "价格",
        },
      ],
      current: 0,
      goods: [],
      // 接口所需参数
      params: {
        query: "",
        cid: "",
        pagenum: 1,
        pagesize: 10,
      },
      total: 0,
    };
  },
  async onLoad({ cid }) {
    this.params.cid = cid;
    this.getGoodsList();
  },
  // 滚动条触底事件
  onReachBottom() {
    // 先判断还有没有下一页数据
    // 拿请求回来的数组总长度与total的值做比较，如果大于等于的话就证明没下一页数据
    if (this.goods.length >= this.total) {
      uni.showToast({
        title: "没有下一页了",
        icon: "none",
      });
      return;
    }
    // 加载下一页数据
    this.params.pagenum++;
    this.getGoodsList();
  },
  // 下拉刷新
  async onPullDownRefresh() {
    // 清空旧数组，重置页码
    this.goods = [];
    this.params.pagenum = 1;
    // 重新发送请求
    await this.getGoodsList();
    // 使用async/await等待数据回来后再关闭下拉刷新
    // 主动关闭下拉刷新
    uni.stopPullDownRefresh();
  },
  methods: {
    click({ index }) {
      this.current = index;
    },
    async getGoodsList() {
      const res = await uni.$u.http.get("/goods/search", {
        params: this.params,
      });
      console.log(res);
      this.goods = [...this.goods, ...res.message.goods];
      this.total = res.message.total;
      console.log("商品列表", this.goods);
    },
  },
};
</script>

<style lang="scss">
.u-tabs__wrapper__nav__line {
  background-color: #eb4450 !important;
}
.goods_item {
  display: flex;
  margin-top: 10rpx;
  .goods_item_img {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: center;
    image {
      width: 191rpx;
      height: 191rpx;
      background-color: #ccc;
    }
  }

  .goods_item_info {
    display: flex;
    flex-direction: column;
    justify-content: space-around;
    font-size: 28rpx;
    color: #666;
    flex: 2;
    .goods_name {
    }

    .goods_price {
      color: #eb4450;
    }
  }
}
</style>